<?php

namespace app\admin\controller;

use app\admin\service\ComImageCateService;
use support\spark\exception\ApiException;
use support\spark\model\system\ComImages;
use support\spark\model\system\ComImagesCate;
use support\Request;
use support\View;

class ComImageCateController extends Curd
{

    /**
     * 获取列表
     */
    public function index()
    {
        if (request()->isAjax()) {
            $comImagesCateModel = new ComImagesCate();
            $list = $comImagesCateModel->getAllList([]);
            return sparkSuccess(dataReturn(0, 'success', makeTree($list)));
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if (request()->isAjaxPost()) {
            $param = request()->post();
            $comImagesCateService = new ComImageCateService();
            $res = $comImagesCateService->addComImageCate($param);
            return sparkSuccess($res);
        }
        return view('com_image_cate/add');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        if (request()->isAjaxPost()) {
            $param = request()->post();

            $comImagesCateService = new ComImageCateService();
            $res = $comImagesCateService->editComImageCate($param);
            return sparkSuccess($res);
        }

        $id = request()->input('id');
        $comImagesCateModel = new ComImagesCate();
        View::assign([
            'info' => $comImagesCateModel->getInfoByWhere([
                'id' => $id
            ])
        ]);

        return view('com_image_cate/edit');
    }

    /**
     * 删除图片分类
     * @param $id
     * @return array
     */
    public function del()
    {
        $id = request()->input('id');
        $comImagesCateModel = new ComImagesCate();
        $hasSub = $comImagesCateModel->getInfoByWhere([
            'pid' => $id
        ], ['id']);
        if (!empty($hasSub)) {
            throw  new ApiException('该分类下有子分类不可删除', -1);

        }

        $comImagesModel = new ComImages();
        $hasUsed = $comImagesModel->getInfoByWhere([
            'cate_id' => $id
        ], ['id']);
        if (!empty($hasUsed)) {
            throw  new ApiException('该分类已经被使用无法删除', -1);
        }
        $comImagesCateModel->delById($id);
        return sparkSuccess(dataReturn(0, '删除成功'));
    }


}